package com.zaizai.service.impl;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.zaizai.properties.AiProperties;
import com.zaizai.service.IAiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
@Slf4j
public class AiServiceImpl implements IAiService {
    @Autowired
    private Generation generation;
    @Autowired
    private AiProperties aiProperties;
    @Override
    public String toTalkResult(String question) throws ApiException, NoApiKeyException, InputRequiredException {
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(question)
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(aiProperties.getAilKey())
                // 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
                .model(aiProperties.getModel())
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();

        GenerationResult call = generation.call(param);
        String result = call.getOutput().getChoices().get(0).getMessage().getContent();
        log.info("question:{}", question);
        log.info("AI返回结果：{}", result);
        return result;
    }
}
